package com.htandroid.htandroid.aty;

/**
 * Created by Administrator on 2015/12/26.
 */

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.model.AbMenuItem;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.ab.view.titlebar.AbTitleBar;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.adapter.ListPopAdapter;
import com.htandroid.htandroid.entity.GcwxList;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.Basenvo;
import com.htandroid.htandroid.sys.DateTimePickDialogUtil;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.webservice.BuildGcwxXMLService;
import com.htandroid.htandroid.webservice.XMLGcwxVouchlist;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

public class Gcwx_jd_detail extends AbActivity {
    public MyApplication myApplication;
    private GcwxList vouch;
    private ArrayList<GcwxList> vouchlist;
    private String initTime = "";
    private String listtype = "0";
    private int icurrentrow;

    private AbTitleBar mAbTitleBar = null;
    private View rightView1 = null;
    private View rightView2 = null;
    private View rightView3 = null;
    private TextView tv_currentrow;

    private AbLoadDialogFragment mDialogFragment = null;
    private PopupWindow popupWindow;
    private ListView popListView;
    private View popView;

    @AbIocView(id = R.id.eswxdate_et)
    EditText eswxdate_et;
    @AbIocView(id = R.id.cwxpname_tv)
    TextView cwxpname_tv;
    @AbIocView(id = R.id.cxzwxpname_tv)
    TextView cxzwxpname_tv;
    @AbIocView(id = R.id.cvouchid_tv)
    TextView cvouchid_tv;
    @AbIocView(id = R.id.eswxdate_iv)
    ImageView eswxdate_iv;
    @AbIocView(id = R.id.cwxpname_iv)
    ImageView cwxpname_iv;
    @AbIocView(id = R.id.cxzwxpname_iv)
    ImageView cxzwxpname_iv;
    @AbIocView(id = R.id.btn1_tv, click = "btnClick")
    TextView btn1_tv;
    @AbIocView(id = R.id.btn2_tv, click = "btnClick")
    TextView btn2_tv;
    @AbIocView(id = R.id.cdepname_tv)
    TextView cdepname_tv;
    @AbIocView(id = R.id.cbxtext_tv)
    TextView cbxtext_tv;
    @AbIocView(id = R.id.ddate_tv)
    TextView ddate_tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_gcwx_jd_detail);
        initview();
    }

    public void btnClick(final View v) {
        switch (v.getId()) {
            case R.id.btn1_tv:
                mDialogFragment = AbDialogUtil.showLoadDialog(this, R.layout.view_dialog_loading, "正在加载...");
                mDialogFragment.setAbDialogOnLoadListener(new AbDialogFragment.AbDialogOnLoadListener() {

                    @Override
                    public void onLoad() {
                        btn1_click(v);
                    }
                });
                break;
            case R.id.btn2_tv:
                mDialogFragment = AbDialogUtil.showLoadDialog(this, R.layout.view_dialog_loading, "正在加载...");
                mDialogFragment.setAbDialogOnLoadListener(new AbDialogFragment.AbDialogOnLoadListener() {

                    @Override
                    public void onLoad() {
                        btn2_click(v);
                    }
                });
                break;
        }
    }

    //初始化
    private void initview() {
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("维修接单");
        mAbTitleBar.setLogo(R.drawable.icon_back);
        mAbTitleBar.getLogoView().setLayoutParams(new LinearLayout.LayoutParams(58, 57));
        mAbTitleBar.getLogoView().setFocusable(true);
        mAbTitleBar.getLogoView().setFocusableInTouchMode(true);
        mAbTitleBar.getLogoView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("currentrow", icurrentrow);//把当前行返回到上一页面,方便更换上一页面的选中行
                setResult(R.layout.basenvo_nofunc / 300000, intent);  //设置返回结果
                //返回时增加提示,防止误点
                finish();
            }
        });
        mAbTitleBar.setTitleBarBackground(R.color.common_title);
        mAbTitleBar.setTitlePadding(118, 0, 0, 0);

        mAbTitleBar.clearRightView();
        rightView1 = mInflater.inflate(R.layout.btn_abs_back, null);
        mAbTitleBar.addRightView(rightView1);
        rightView2 = mInflater.inflate(R.layout.tv_currentrow, null);
        mAbTitleBar.addRightView(rightView2);
        rightView3 = mInflater.inflate(R.layout.btn_abs_forward, null);
        mAbTitleBar.addRightView(rightView3);
        tv_currentrow = (TextView) rightView2.findViewById(R.id.tv_currentrow);

        //获取传递的对象参数
        Intent intent = getIntent();
        vouchlist = (ArrayList<GcwxList>) intent.getSerializableExtra("vouchlist");
        listtype = intent.getExtras().getString("listtype");
        icurrentrow = getIntent().getExtras().getInt("currentrow");

        insert_data(icurrentrow);

        popView = mInflater.inflate(R.layout.list_pop, null);
        popListView = (ListView) popView.findViewById(R.id.pop_list);
        popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        AnimationSet animationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 1, 1, Animation.ZORDER_BOTTOM, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animationSet.setDuration(250);
        animationSet.addAnimation(scaleAnimation);
        popView.startAnimation(animationSet);
        ImageView more_close = (ImageView) popView.findViewById(R.id.item_close);
        more_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
    }

    //为窗口填充数据
    public void insert_data(int row) {
        vouch = vouchlist.get(row);
        icurrentrow = row;
        tv_currentrow.setText((icurrentrow + 1) + "/" + (vouchlist.size()));
        //接单和取消接单
        if (listtype.equals("0")) {
            showwin(true);
            //隐藏取消接单
            btn2_tv.setVisibility(View.GONE);
        } else {
            showwin(false);
            //隐藏保存
            btn1_tv.setVisibility(View.GONE);
        }
        //填写文本内容
        cvouchid_tv.setText(vouch.getCvouchid());
        if (!vouch.getCdepcode().equals("")) {
            cdepname_tv.setText(vouch.getCdepname());
            cdepname_tv.setTag(vouch.getCdepcode());
        }

        cbxtext_tv.setText(vouch.getCbxtext());
        ddate_tv.setText(Basenvo.customDateFormat("yyyy-MM-dd HH:mm", vouch.getDdate()));

        if (!vouch.getEswxdate().equals("")) {
            initTime = Basenvo.customDateFormat("yyyy-MM-dd HH:mm", vouch.getEswxdate());
        } else {
            Date curDate = new Date(System.currentTimeMillis());
            initTime = Basenvo.customDateFormat("yyyy-MM-dd HH:mm", curDate);
        }
        eswxdate_et.setText(initTime);
        //已接信息
        if (!Basenvo.equal(vouch.getCwxpname(), "")) {
            cwxpname_tv.setText(vouch.getCwxpname());
            cwxpname_tv.setTag(vouch.getCwxpcode());
        } else {
            cwxpname_tv.setText("");
            cwxpname_tv.setTag("");
        }
        if (!Basenvo.equal(vouch.getXzwxnames(), "")) {
            cxzwxpname_tv.setText(vouch.getXzwxnames());
            cxzwxpname_tv.setTag(vouch.getXzwxcodes());
        } else {
            cxzwxpname_tv.setText("");
            cxzwxpname_tv.setTag("");
        }
        //变更表头数据
        insert_data_title();
    }

    public void insert_data_title() {
        //表头信息显示弹窗
        ImageView listmore_iv = (ImageView) findViewById(R.id.titlemore_iv);
        listmore_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final ImageView imgs = (ImageView) v;
                Map<AbMenuItem, AbMenuItem> map1 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map2 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map3 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map4 = new HashMap<AbMenuItem, AbMenuItem>();
                Map<AbMenuItem, AbMenuItem> map5 = new HashMap<AbMenuItem, AbMenuItem>();
                map1.put(new AbMenuItem("报修区域："), new AbMenuItem(vouch.getCwxplname()));
                map2.put(new AbMenuItem("报修等级："), new AbMenuItem(vouch.getCdjname()));
                map3.put(new AbMenuItem("报修类型："), new AbMenuItem(vouch.getCtypename()));
                map4.put(new AbMenuItem("维修类别："), new AbMenuItem(""));
                map5.put(new AbMenuItem("    报修人："), new AbMenuItem(vouch.getCmaker()));
                ArrayList<Map<AbMenuItem, AbMenuItem>> data = new ArrayList<Map<AbMenuItem, AbMenuItem>>();
                data.add(map1);
                data.add(map2);
                data.add(map3);
                data.add(map4);
                data.add(map5);
                ListPopAdapter mListPopAdapter = new ListPopAdapter(Gcwx_jd_detail.this, data, R.layout.list_popitem);
                popListView.setAdapter(mListPopAdapter);
                //弹出窗口后,变更更多图标
                imgs.setImageResource(R.drawable.item_more_choose);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    public void onDismiss() {
                        //还原图标
                        imgs.setImageResource(R.drawable.item_more);
                    }
                });
                popupWindow.showAsDropDown(v);
            }
        });
    }

    //选择
    public void cwxp_choose(View v) {
        String btntype = v.getTag().toString();
        String cwxpcode = "", cxzwxpcode = "";
        //选择维修员
        if (cwxpname_tv.getTag() != null) {
            cwxpcode = cwxpname_tv.getTag().toString();
        }
        if (btntype.equals("wxp")) {
            Intent intent = new Intent(getApplicationContext(), Basenvo_Choosewxperson.class);
            // 设置传递数据
            intent.putExtra("btntype", btntype);
            intent.putExtra("ccode", cwxpcode);
            startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
        } else {
            if (cwxpcode == null | cwxpcode.equals("")) {
                AbToastUtil.showToastInThread(getApplicationContext(), "请先选择主维修人!");
                return;
            }
            //选择协助维修人
            if (cxzwxpname_tv.getTag() != null) {
                cxzwxpcode = cxzwxpname_tv.getTag().toString();
            }
            Intent intent = new Intent(getApplicationContext(), Basenvo_ChooseXzwxperson.class);
            // 设置传递数据
            intent.putExtra("btntype", btntype);
            intent.putExtra("ccodes", cxzwxpcode);
            intent.putExtra("ccode", cwxpcode);
            startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
        }
    }

    //选择时间
    public void eswxdate_choose(View v) {
        initTime = eswxdate_et.getText().toString();
        DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                Gcwx_jd_detail.this, initTime);
        dateTimePicKDialog.dateTimePicKDialog(eswxdate_et);
    }

    public void showwin(boolean stype) {
        //背景变白，字变黑色
        Integer backgroundcolor = Color.TRANSPARENT;
        if (stype) {
            eswxdate_iv.setVisibility(View.VISIBLE);
            cwxpname_iv.setVisibility(View.VISIBLE);
            cxzwxpname_iv.setVisibility(View.VISIBLE);

            eswxdate_et.setBackgroundResource(R.drawable.edit_background);
            cwxpname_tv.setBackgroundResource(R.drawable.edit_background);
            cxzwxpname_tv.setBackgroundResource(R.drawable.edit_background);
        } else {
            eswxdate_iv.setVisibility(View.GONE);
            cwxpname_iv.setVisibility(View.GONE);
            cxzwxpname_iv.setVisibility(View.GONE);

            eswxdate_et.setBackgroundColor(backgroundcolor);
            cwxpname_tv.setBackgroundColor(backgroundcolor);
            cxzwxpname_tv.setBackgroundColor(backgroundcolor);
        }
    }

    //维修接单
    public void btn1_click(View v) {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                //必须有主维修人
                if (Basenvo.equal(vouch.getCwxgcode(), "")) {
                    AbDialogUtil.removeDialog(Gcwx_jd_detail.this);
                    AbToastUtil.showToastInThread(getApplicationContext(), "必须选择维修人!");
                    return;
                }
                vouch.setEswxdate(eswxdate_et.getText().toString());
                String urlString = "http://" + InstorageURL.SERVERURL
                        + BaseUrl_New;
                String[] parms = {"username", "cacc_id", "iyear"};
                String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year()};
                //生成xml
                BuildGcwxXMLService service = new BuildGcwxXMLService();
                String xmlstring = service.buildXML("gcwx_jdsave", InstorageURL.NAME_SPACE, parms, vals, "in" + String.valueOf(parms.length), vouch, null, null, null, null, null, null);
                mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "gcwx_jdsave", xmlstring, new AbSoapUtil.WebServiceCallBack() {
                    @Override
                    public void onSucced(String result) {
                        if (result != null) {
                            //解析xml文件,返回列表
                            List<GcwxList> vouchlist = XMLGcwxVouchlist.paraseCommentInfors(result);
                            //默认显示第一行数据
                            if (vouchlist.size() > 0) {
                                vouch = vouchlist.get(0);
                            }
                            if (vouch.getSucstatus().equals("0")) {
                                AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!");
                            } else {
                                Intent intent = new Intent();
                                setResult(R.layout.layout_gcwx_jd_detail / 100000, intent);  //设置返回结果
                                finish();
                            }
                        } else {
                            AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!数据库错误!");
                        }
                        AbDialogUtil.removeDialog(Gcwx_jd_detail.this);
                    }

                    @Override
                    public void onFailure(String result) {
                        AbDialogUtil.removeDialog(Gcwx_jd_detail.this);
                        AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!数据库错误!");
                    }
                });
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        });
        mAbTask.execute(item);
    }

    //维修接单取消
    public void btn2_click(View v) {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener() {

            @Override
            public void update() {
                String urlString = "http://" + InstorageURL.SERVERURL
                        + BaseUrl_New;
                String[] parms = {"username", "cacc_id", "iyear", "ctype"};
                String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), "jd"};
                //生成xml
                BuildGcwxXMLService service = new BuildGcwxXMLService();
                String xmlstring = service.buildXML("gcwx_qx", InstorageURL.NAME_SPACE, parms, vals, "in" + String.valueOf(parms.length), vouch, null, null, null, null, null, null);
                mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "gcwx_qx", xmlstring, new AbSoapUtil.WebServiceCallBack() {
                    @Override
                    public void onSucced(String result) {
                        if (result != null) {
                            //解析xml文件,返回列表
                            List<GcwxList> vouchlist = XMLGcwxVouchlist.paraseCommentInfors(result);
                            //默认显示第一行数据
                            if (vouchlist.size() > 0) {
                                vouch = vouchlist.get(0);
                            }
                            if (vouch.getSucstatus().equals("0")) {
                                AbToastUtil.showToastInThread(getApplicationContext(), "单据删除失败!");
                            } else {
                                Intent intent = new Intent();
                                setResult(R.layout.layout_gcwx_jd_detail / 100000, intent);  //设置返回结果
                                finish();
                            }
                        } else {
                            AbToastUtil.showToastInThread(getApplicationContext(), "单据删除失败!数据库错误!");
                        }
                        AbDialogUtil.removeDialog(Gcwx_jd_detail.this);
                    }

                    @Override
                    public void onFailure(String result) {
                        AbDialogUtil.removeDialog(Gcwx_jd_detail.this);
                    }
                });
            }

            @Override
            public void get() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        });
        mAbTask.execute(item);
    }

    //接收返回数据(供应商和存货明细)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case R.layout.basenvo_rchoose / 200000:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    String ccode = bundle.getString("ccode");
                    String cname = bundle.getString("cname");
                    String cgcode = bundle.getString("cgcode");
                    String cgname = bundle.getString("cgname");
                    String btntype = bundle.getString("btntype");
                    if (btntype.equals("wxp")) {
                        cwxpname_tv.setText(cname);
                        cwxpname_tv.setTag(ccode);
                        vouch.setCwxpcode(ccode);
                        vouch.setCwxpname(cname);
                        vouch.setCwxgcode(cgcode);
                        vouch.setCwxgname(cgname);
                    } else {
                        //协助维修
                        cxzwxpname_tv.setText(cname);
                        cxzwxpname_tv.setTag(ccode);
                        vouch.setXzwxnames(cname);
                        vouch.setXzwxcodes(ccode);
                    }
                }
                break;
            default:
                //其它窗口的回传数据
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //向左翻页
    public void btn_abs_back(View v) {
        if (icurrentrow == 0) {
            AbToastUtil.showToastInThread(getApplicationContext(), "已经是第一项!");
        } else {
            insert_data(icurrentrow - 1);
        }
    }

    //向右翻页
    public void btn_abs_forward(View v) {
        if (icurrentrow == (vouchlist.size() - 1)) {
            AbToastUtil.showToastInThread(getApplicationContext(), "已经是最后一项!");
        } else {
            insert_data(icurrentrow + 1);
        }
    }
}

